package com.xiangty.test;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionUtil {

	public static SqlSession getSqlSession() {
		SqlSession sqlSession = null;
		// 此处可以不使用try抛异常，SqlSessionFactoryBuilder().build()方法中有reader流关闭的操作
		try (Reader reader = Resources.getResourceAsReader("mybatis-config.xml");) {
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			sqlSession = sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sqlSession != null) {
			return sqlSession;
		} else {
			throw new NullPointerException("sqlSession为空");
		}
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		// 此处可以不使用try抛异常，SqlSessionFactoryBuilder().build()方法中有reader流关闭的操作
		try (Reader reader = Resources.getResourceAsReader("mybatis-config.xml");) {
			return new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
